package com.tchintech.pay.view.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.tchintech.pay.MyApplication;
import com.tchintech.pay.R;
import com.tchintech.pay.delegate.LoginDelegate;
import com.tchintech.pay.frame.presenter.ActivityPresenter;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.User;
import com.tchintech.pay.model.entity.Version;
import com.tchintech.pay.net.DownLoadManager;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.AppConst;
import com.tchintech.pay.utils.AppTool;
import com.tchintech.pay.utils.RegexUtils;
import com.tchintech.pay.widget.DialogWiget;

import org.json.JSONObject;

/**
 * Created by Administrator on 2017/7/3 0003.
 * <p>
 * 登录界面
 */

public class LoginActivity extends ActivityPresenter<LoginDelegate> implements View.OnClickListener {

    private MyApplication myApplication;
    protected HashMap<String, String> map;
    private final String urlLogin = "Login.login";
    private String urlUpdata = "Version.update";
    private Intent intent = new Intent();
    private User user = new User();
    private Handler handler;
    //注册界面回传标识
    private static final int REGISTER_STATE = 1200;
    private DialogWiget dialog = new DialogWiget();
    //帐号密码
    private String phoneNumber, password;
    public static List<Activity> aList;

    @Override
    protected Class<LoginDelegate> getDelegateClass() {
        return LoginDelegate.class;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //注册点击事件

    @Override
    protected void initView() {
        super.initView();
        myApplication = MyApplication.getInstance();
        //读取手机号存储****
        viewDelegate.getEdittView(R.id.login_ed_phoneNumber).setText(getSpUtils().read("phoneNumber"));
        viewDelegate.setOnClickListener(this, R.id.login_bt_login, R.id.login_bt_register, R.id.login_bt_lostPassword, R.id.bt_test);
        handler();
        updata();

    }


    /**
     * 自动登录
     */

    private void remberLogin() {
        phoneNumber = getSpUtils().read("phoneNumber");
        password = getSpUtils().read("passWord");
        if (!phoneNumber.equals("") && !password.equals("")) {
            VerData(phoneNumber, password);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_bt_login:
                phoneNumber = viewDelegate.getText(R.id.login_ed_phoneNumber);
                password = viewDelegate.getText(R.id.login_ed_password);
                VerData(phoneNumber, password);
                // Phphttp();
                break;
            case R.id.login_bt_register:
                //注册按钮
                intent.setClass(this, RegisterActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.login_bt_lostPassword:
                intent.setClass(this, LostPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.bt_test:
                showMsg("支付SDK测试");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    //读取手机号存储   这里不做判断 只要回来就去缓存里面拿手机号
                    viewDelegate.getEdittView(R.id.login_ed_phoneNumber).setText(getSpUtils().read("phoneNumber"));
                }
                break;
        }
    }

    /**
     * 登陆验证
     */
    private void VerData(String phoneNumber, String password) {
        map = new HashMap<>();
        if (RegexUtils.checkPhoneNumber(phoneNumber)) {
            if (!"".equals(password)) {
                map.put("phoneNumber", phoneNumber);
                map.put("password", password);
                showProgressDialog("", "加载中，请稍后...");
                new OkhttpClientTest().path(this, handler, urlLogin, map, HttpCode.login);
            } else {
                viewDelegate.getTextViews(R.id.login_tv_tips).setText("请输入密码");
            }
        } else {
            viewDelegate.getTextViews(R.id.login_tv_tips).setText("请输入正确的手机号");
        }

    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                hideProgressDialog();
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.login:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                getSpUtils().write("phoneNumber", phoneNumber);
                                getSpUtils().write("passWord", password);
                                User user = getGson().fromJson(json.getString("data"), User.class);
                                System.out.println("登录返回值：" + user);
                                AppConst.setUser(user);
                                intent.setClass(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else if (json.getString("ret").equals("2")) {
                                aList = new ArrayList<Activity>();
                                aList.add(LoginActivity.this);
                                intent.setClass(LoginActivity.this, BoundcaedActivity.class);
                                intent.putExtra("id", json.getString("msg"));
                                intent.putExtra("isfirst", true);
                                intent.putExtra("bound_enter", "0");
                                startActivity(intent);
                            } else {
                                showMsg(json.getString("msg").toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case HttpCode.update:
                        try {
                            Version version = getGson().fromJson(msg.obj.toString(), Version.class);
                            if (version.getRet().equals("0")) {
                                showUpdataDialog("0", version.getMsg());
                            } else if (version.getRet().equals("2")) {
                                showUpdataDialog("2", version.getMsg());
                            } else {
                                //不需要更新，直接登录
                                remberLogin();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showMsg("未知的错误");
                        }
                        break;
                    case HttpCode.timeout:
                        showMsg(msg.obj.toString());
                        break;
                }
            }
        }

        ;
    }


    /**
     * 检查更新
     */
    private void updata() {
        showProgressDialog("", "加载中，请稍后...");
        map = new HashMap<String, String>();
        int viscode = AppTool.getVersionCode(getApplicationContext());
        map.put("version_num", viscode + "");
        new OkhttpClientTest().path(this, handler, urlUpdata, map, HttpCode.update);
    }

    /**
     * 弹出更新对话框
     */
    public void showUpdataDialog(final String type, String content) {
        //获取手机型号
        final String model = android.os.Build.MODEL;
        if (model.contains("POS")) {
            dialog.showCustomMessageQuery(this, "应用更新", "请到应用市场更新");
        } else {
            dialog.showCustomMessageQuery(this, "应用更新", content);
        }

        dialog.setOnQueryOkListener(new DialogWiget.OnQueryOk() {

            @Override
            public void onQueryOkClick(View v) {
                //System.out.println("点击确定按钮");
                if (!model.contains("POS")) {
                    downLoadApk();
                }

            }
        });
        dialog.setOnQueryCancelListener(new DialogWiget.OnQueryCancel() {

            @Override
            public void onQueryCancel(View v) {
                //强制更新点否 推出登录
                //0 更新但不强制  1 不更新   2 强制更新
                if (type.equals("2") && !model.contains("POS")) {
                    //强制更新，若不更新则推出
                    logout();
                } else {
                    //不强制更新，点击取消还能继续登录
                    remberLogin();
                }

            }
        });
    }


    private ProgressDialog pd;
    protected boolean run = true;
    //服务器下载地址
    //固定地址 无需更改
    private String httpurl = "http://117.34.105.60/qzn.apk";

    /**
     * 下载apk
     */
    public void downLoadApk() {
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在下载更新");
        pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                run = false;
                // 断开DownLoadManager网络连接
                // 结束
                finish();
            }
        });
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(httpurl, pd);
                    System.out.println("下载文件" + file);
                    sleep(50);
                    if (run) {
                        AppTool.installApk(file);
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = HttpCode.DOWN_ERROR;
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }

    /**
     * 退出程序
     */
    private void logout() {
        System.exit(0);
    }
}
